package cn.keyvalue.ccf.common.util;

import java.awt.Image;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

public class ImageUtils {

	/**
	 * 判断图片格式
	 * 
	 * 根据文件前10个byte去判断文件格式
	 * 
	 * @param args
	 * @throws IOException
	 */
	public static String getImageType(File imageFile) throws IOException {

		if (imageFile != null && imageFile.exists()) {
			byte[] bytes = FileUtils.readFileToByteArray(imageFile);

			if (bytes.length > 10) {
				String headerStr = new String(ArrayUtils.subarray(bytes, 0, 10));

				if (StringUtils.containsIgnoreCase(headerStr, "gif")) {
					return "gif";
				}

				if (StringUtils.containsIgnoreCase(headerStr, "PNG")) {
					return "png";
				}

				if (StringUtils.containsIgnoreCase(headerStr, "JFIF")) {
					return "jpg";
				}
			}
		}

		return null;
	}

	/**
	 * 获取文件尺寸，内部做了格式校验 宽×高
	 * 
	 * @param imageFile
	 * @return
	 * @throws IOException
	 */
	public static int[] getImageSize(File imageFile) throws IOException {
		
		Image src = ImageIO.read(imageFile);     // 构造Image对象
		int wideth = (int) src.getWidth(null);   // 得到源图宽
		int height = (int) src.getHeight(null);  // 得到源图长	  
		
		return new int[]{wideth,height};
	}
	
	
	public static void main( String[] args ) throws IOException
	{
		File f = new File("D:\\PrivateFiles\\Pictures\\QQ图片20130716171948");
		System.out.println( ArrayUtils.toString( getImageSize(f) ) );
	}
}
